
// 前台访问API
const express = require('express')
const router = express.Router()
const User = require('../models/User')
const Article = require('../models/Article')
const Category = require('../models/Category')
const Comment = require('../models/Comment')


// 统一返回格式
let responseData
// 每一次进入路由都使用这个模块
router.use(function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	next()
})

// 前台注册接口  /front/register
/**
 * 注册逻辑
 * 	1.用户名不能为空
 * 	2.密码不能为空
 * 	3.两次输入密码必须一致
 * 数据库
 * 	1.用户名是否已经被注册了
 * 		数据库查询
 */
router.post('/register', function(req, res, next) {
	const { username, password, repassword } = req.body

	if(!username) {
		responseData.resultCode = 1
		responseData.resultMsg = '用户名不能为空'
		res.json(responseData)
		return
	}

	if(!password) {
		responseData.resultCode = 1
		responseData.resultMsg = '密码不能为空'
		res.json(responseData)
		return
	}

	if(password !== repassword) {
		responseData.resultCode = 1
		responseData.resultMsg = '两次输入密码不一致'
		res.json(responseData)
		return
	}

	User.findOne({
		username: username
	}).then(function(userInfo) {
		if(userInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户名已经存在'
			res.json(responseData)
			return
		}

		// 保存用户信息
		let user = new User({
			username: username,
			password: password
		})
		return user.save()
	}).then(function(newUserInfo) {
		console.log(newUserInfo)
		responseData.resultMsg = '注册成功'
		res.json(responseData)
	})
})

/** 前台登陆接口  /front/login
 * 登陆逻辑
 * 1.判断用户名和密码是否为空
 * 2.数据库判断是否错误
 *
 */
router.post('/login', function(req, res, next) {
	const { username, password } = req.body
	if(!username || !password) {
		responseData.resultCode = 1
		responseData.resultMsg = '用户名或者密码不能为空'
		res.json(responseData)
		return
	}
	User.findOne({
		username: username,
		password: password
	}).then(function(userInfo) {
		if(!userInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户名或者密码错误'
			res.json(responseData)
			return
		}
		responseData.resultMsg = '登陆成功'

		// 登陆成功设置cookies,让用户下次访问携带cookies值
		// cookies的操作应该是响应头写入cookie信息，然后返回到浏览器将这份信息存入浏览器的cookie当中
		req.cookies.set('userInfo', JSON.stringify({
			_id: userInfo._id,
			username: userInfo.username
		}))

		res.json(responseData)
		return
	})
})

/** 前台退出登陆  /front/logout
 * 
 */
router.get('/logout', function (req, res) {
  req.cookies.set('userInfo', null);
  responseData.resultMsg = '退出成功'
  res.json(responseData);
})


router.get('/article', function(req, res) {
	Article.find().then(function(articleList) {
		responseData.data['list'] = articleList
		res.json(responseData)
		return
	})
})


/**
 * 前台查询某一条博客接口  /front/article/detail
 */
router.get('/article/detail', function(req, res) {
	console.log(req.query)
	if(JSON.stringify(req.query) == '{}') {
		responseData.resultCode = 1
		responseData.resultMsg = '请传入参数'
		res.json(responseData)
		return
	}
	Article.findOne({...req.query}).then(function(articleInfo) {
		if(articleInfo) {
			responseData.data = articleInfo
			res.json(responseData)
			return
		}else {
			responseData.resultCode = 1
			responseData.resultMsg = '不存在这条数据'
			res.json(responseData)
		}
	}, function(err) {
		console.log(err)
	})
})

/** 前台查询标签列表接口 /category
 * 
 */
router.get('/category', function(req, res, next) {
	Category.find().then(function(categoryList) {
		responseData.data['list'] = categoryList
		responseData.resultCode = 0
		responseData.resultMsg = 'success'
		res.json(responseData)
		return
	})
})


/** 根据标签查询文章列表 /category
 * 
 */
router.get('/category/article', function(req, res, next) {
	console.log(req.query)
	if(!req.query.articleTag) {
		responseData.resultCode = 1
		responseData.resultMsg = '参数不能为空'
		res.json(responseData)
		return
	}
	Article.find({
		articleTag: req.query.articleTag
	}).then((articleList) => {
		responseData.resultCode = 0
		responseData.resultMsg = 'success'
		responseData.data = articleList
		res.json(responseData)
	})
})


/** 添加评论
 * 
 */
router.post('/article/comment', function(req, res, next) {
	// 参数： 博客ID，nickName, email, content, parentID
	// 如果parentID为空，那么直接插入评论，如果parentID不为空，那么往这里面加入

	let {_id, nickName, email, content, parentID} = req.body
	if(!_id) {
		responseData.resultCode = 1
		responseData.resultMsg = '参数错误'
		res.json(responseData)
		return
	}
	// 判断parentID是否为空
	if(parentID) {
		Comment.updateOne({
			_id: parentID
		}, {
			$push: {"children": { nickName, email, content, time: new Date().toLocaleString() }}
		}).then(result => {
			if(result.nModified + '' !== '0') {
				responseData.resultCode = 0
				responseData.resultMsg = 'success'
				responseData.data.articleId = _id
				res.json(responseData)
			}
			responseData.resultCode = 1
			responseData.resultMsg = 'fail'
			res.json(responseData)
		})
	}else {
		let comment = new Comment({articleId: _id, nickName, email, content, time: new Date().toLocaleString()})
		comment.save().then(commentInfo => {
			if(commentInfo) {
				responseData.resultCode = 0
				responseData.resultMsg = 'success'
				responseData.data.articleId = _id
				res.json(responseData)
			}
		})
	}
})

/** 查询文章下面所有的评论
 * 
 */
router.get('/article/comment', function(req, res, next) {
	let articleId = req.query.articleId
	Comment.find({
		articleId
	}).then(commentList => {
		responseData.data = commentList
		responseData.resultCode = 0
		responseData.resultMsg = 'success'
		res.json(responseData)
	})
})

/**
 * 搜索文章
 * 
 */
router.get('/search', function(req, res, next) {
	console.log(req.param('value'))
	let result = []
	Article.find().then(articleList => {
		articleList.forEach((item, index) => {
			// 判断是否包含字符串
			console.log(item.articleTitle)
			if(item.articleTitle.indexOf(req.param('value')) != -1) {
				result.push(item)			
			}
		})
		res.json(result)
	})


	// res.send(req.param('value'))
})


module.exports = router